//
//  BQLogInVc.m
//  BeeQuick
//
//  Created by GuoDeJin on 2016/11/22.
//  Copyright © 2016年 six_group. All rights reserved.
//

#import "BQLogInVc.h"
#import "Masonry.h"
#import "UIColor+CZAddition.h"
#import <SMS_SDK/SMSSDK.h>
#import "SVProgressHUD.h"
@interface BQLogInVc ()

@property (nonatomic,weak) UITextField *phoneNumField;

@property (nonatomic,weak) UITextField *codeNumField;

@property (nonatomic,weak) UIButton *dengLuBtn;

@property (nonatomic,weak) UIButton *yanZhengMaBtn;
@end

@implementation BQLogInVc

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
}


- (void)setupUI{
    
    
    //自定义导航条返回按钮
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"v2_goback"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonOF)];
    
    
    self.navigationItem.leftBarButtonItem = barButtonItem;

    
    self.navigationItem.title = @"登录";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //text1
    UITextField *numberText = [[UITextField alloc]init];
    numberText.placeholder = @"请输入手机号";
    numberText.font = [UIFont systemFontOfSize:12];
    _phoneNumField = numberText;
    [self.view addSubview:numberText];
    
    //L1
    UILabel *xian1 = [[UILabel alloc]init];
    xian1.backgroundColor = [UIColor cz_colorWithRed:215 green:215 blue:215];
    [self.view addSubview:xian1];
    
    //text2
    UITextField *yanZhengText = [[UITextField alloc]init];
    yanZhengText.placeholder = @"请输入验证码";
    yanZhengText.font = [UIFont systemFontOfSize:12];
    _codeNumField = yanZhengText;
    [self.view addSubview:yanZhengText];
    
    
    //L2
    UILabel *xian2 = [[UILabel alloc]init];
    xian2.backgroundColor = [UIColor cz_colorWithRed:215 green:215 blue:215];
    [self.view addSubview:xian2];
    
    
    //获取验证码
    UIButton *huoQuBtn = [[UIButton alloc]init];
    [huoQuBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [huoQuBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    huoQuBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [huoQuBtn addTarget:self action:@selector(huoQuYanZhengMa) forControlEvents:UIControlEventTouchUpInside];
    self.yanZhengMaBtn = huoQuBtn;
    [self.view addSubview:huoQuBtn];
    
    //竖线
    UILabel *shuXian = [[UILabel alloc]init];
    shuXian.backgroundColor = [UIColor cz_colorWithRed:215 green:215 blue:215];
    [self.view addSubview:shuXian];
    
    //登录按钮
    UIButton *logInBtn = [[UIButton alloc]init];
    logInBtn.backgroundColor = [UIColor cz_colorWithRed:215 green:215 blue:215];
    [logInBtn setTitle:@"登   录" forState:UIControlStateNormal];
    [logInBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    
    [logInBtn addTarget:self action:@selector(dengLu) forControlEvents:UIControlEventTouchUpInside];
    //监听验证码有没有输入的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:UITextFieldTextDidChangeNotification object:yanZhengText];
    
    self.dengLuBtn = logInBtn;
    [self.view addSubview:logInBtn];
    
    
    //登录下提示label
    UILabel *tiShi = [[UILabel alloc]init];
    tiShi.text = @"收不到短信? 使用";
    tiShi.font = [UIFont systemFontOfSize:12];
    tiShi.textColor = [UIColor grayColor];
    [self.view addSubview:tiShi];
    
    //语音验证
    UIButton *yuYinBtn = [[UIButton alloc]init];
    [yuYinBtn setTitle:@"语音验证" forState:UIControlStateNormal];
    [yuYinBtn setTitleColor:[UIColor cz_colorWithRed:78 green:135 blue:255] forState:UIControlStateNormal];
    yuYinBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [yuYinBtn addTarget:self action:@selector(yuYin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:yuYinBtn];
    
    
    
    
    
    //手机号约束
    [numberText mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.offset(120);
        make.left.equalTo(self.view).offset(3);
        make.width.mas_equalTo(250);
    }];
    
    //横线1
    [xian1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(numberText.mas_bottom).offset(13);
        make.right.equalTo(self.view);
        make.left.equalTo(self.view).offset(5);
        make.height.mas_equalTo(1);
    }];
    
    //验证码
    [yanZhengText mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(xian1.mas_bottom).offset(13);
        make.left.equalTo(self.view).offset(3);
        make.width.mas_equalTo(250);
    }];
    
    //横线2
    [xian2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(yanZhengText.mas_bottom).offset(13);
        make.right.equalTo(self.view);
        make.left.equalTo(self.view).offset(5);
        make.height.mas_equalTo(1);
    }];
    
    //获取验证码约束
    [huoQuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.top.equalTo(xian1.mas_bottom).offset(5);
    }];
    
    
    //竖线约束
    [shuXian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(yanZhengText.mas_right).offset(30);
        make.top.equalTo(xian1.mas_bottom).offset(5);
        make.bottom.equalTo(xian2.mas_top).offset(-5);
        make.width.mas_equalTo(1);
    }];
    
    //登录按钮约束
    [logInBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(xian2.mas_bottom).offset(50);
        make.left.mas_equalTo(8);
        make.right.mas_equalTo(-8);
    }];
    
    //提示label约束
    [tiShi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX).offset(-25);
        make.top.equalTo(logInBtn.mas_bottom).offset(10);
        
    }];
    
    //语音验证按钮约束
    [yuYinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tiShi.mas_centerY).offset(-1);
        make.left.equalTo(tiShi.mas_right).offset(5);
    }];
    
    
    
    
    
}
//监听验证码有么有超过4位  改变登录按钮背景色
-(void)change:(NSNotification *)notification
{
    if (_phoneNumField.text.length == 11 && _codeNumField.text.length == 4) {
        self.dengLuBtn.backgroundColor = [UIColor cz_colorWithRed:255 green:200 blue:20];
        [self.dengLuBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.dengLuBtn.userInteractionEnabled = YES;
    }else
    {
        
        self.dengLuBtn.backgroundColor = [UIColor cz_colorWithRed:215 green:215 blue:215];
        [self.dengLuBtn setTitle:@"登   录" forState:UIControlStateNormal];
        [self.dengLuBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.dengLuBtn.userInteractionEnabled = NO;
        
    }
    
}


#pragma mark - 获取验证码的点击事件
-(void)huoQuYanZhengMa{
    
    
    if(_phoneNumField.text.length != 11){
        
        [SVProgressHUD showInfoWithStatus:@"请检查手机号码是否正确"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
        });
    }
    
    if (_phoneNumField.text.length == 11) {
        NSString *phoneNumber = self.phoneNumField.text;
        NSLog(@" %@ ",phoneNumber);
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:phoneNumber zone:@"86" customIdentifier:nil result:^(NSError *error) {
            if (!error) {
                [SVProgressHUD  showWithStatus:@"验证码发送成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD dismiss];
                });
                NSLog(@"验证码发送成功");
            }else{
                [SVProgressHUD showWithStatus:@"发送失败"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD dismiss];
                });
                NSLog(@"发送失败");
                NSLog(@"%ld",(long)error.code);
            }
        }];
        
        
        //获取完验证码改变按钮样式为倒计时  再关掉用户交互
        __block int timeout=30; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.yanZhengMaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                    self.yanZhengMaBtn.userInteractionEnabled = YES;
                });
            }else{
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    //NSLog(@"____%@",strTime);
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:1];
                    [self.yanZhengMaBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                    [UIView commitAnimations];
                    self.yanZhengMaBtn.userInteractionEnabled = NO;
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
        
        
    }
}
#pragma mark - 登录按钮点击事件
- (void)dengLu{
    
    
    NSString *codeNumber = self.codeNumField.text;
    NSString *phoneNumber = self.phoneNumField.text;
    
    if (_phoneNumField.text.length != 11 && _codeNumField.text.length != 4) {
        
        //        self.dengLuBtn.userInteractionEnabled = NO;
        
        [SVProgressHUD showInfoWithStatus:@"认真检查输入是否正确哦~"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
        });
        
    }else{
        
        
        [SMSSDK commitVerificationCode:codeNumber phoneNumber:phoneNumber zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
            
            if (!error) {
                
                [SVProgressHUD showWithStatus:@"验证成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD dismiss];
                });
                NSLog(@"登录成功");
                //MARK: 登录成功
                
                
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"loadSucess" object:phoneNumber];
                
                
                [self.navigationController popViewControllerAnimated:YES];
                //
            }else{
                [SVProgressHUD showWithStatus:@"验证失败"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD dismiss];
                });
                NSLog(@"验证失败");
                NSLog(@"%@",error);
            }
        }];
    }
    
}
#pragma mark - 语音验证码点击事件
- (void)yuYin{
    
    if(_phoneNumField.text.length != 11){
        
        [SVProgressHUD showInfoWithStatus:@"请检查手机号码是否正确"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
        });
    }
    
    if (_phoneNumField.text.length == 11) {
        NSString *phoneNumber = self.phoneNumField.text;
        NSLog(@" %@ ",phoneNumber);
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodVoice phoneNumber:phoneNumber zone:@"86" customIdentifier:nil result:^(NSError *error) {
            if (!error) {
                [SVProgressHUD  showWithStatus:@"请留意接听验证码电话"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD dismiss];
                });
                NSLog(@"验证码发送成功");
            }else{
                [SVProgressHUD showWithStatus:@"操作失败"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    [SVProgressHUD dismiss];
                });
                NSLog(@"发送失败");
                NSLog(@"%ld",(long)error.code);
            }
        }];
        
        
        //获取完验证码改变按钮样式为倒计时  再关掉用户交互
//        __block int timeout=30; //倒计时时间
//        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
//        dispatch_source_set_event_handler(_timer, ^{
//            if(timeout<=0){ //倒计时结束，关闭
//                dispatch_source_cancel(_timer);
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    //设置界面的按钮显示 根据自己需求设置
//                    [self.yanZhengMaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
//                    self.yanZhengMaBtn.userInteractionEnabled = YES;
//                });
//            }else{
//                int seconds = timeout % 60;
//                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    //设置界面的按钮显示 根据自己需求设置
//                    //NSLog(@"____%@",strTime);
//                    [UIView beginAnimations:nil context:nil];
//                    [UIView setAnimationDuration:1];
//                    [self.yanZhengMaBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
//                    [UIView commitAnimations];
//                    self.yanZhengMaBtn.userInteractionEnabled = NO;
//                });
//                timeout--;
//            }
//        });
//        dispatch_resume(_timer);
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)dealloc
{
    //销毁通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    
    
}


-(void)buttonOF{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
